package com.gnl.scheduler.common;

import java.util.Map;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class EventsSender {

    private Connection connection = null;
    private InitialContext initialContext = null;
    private Session session = null;
    private MessageProducer producer = null;

    public void init() throws NamingException, JMSException {
        //init JMS connection

        //Create an initial context to perform the JNDI lookup.
        initialContext = new InitialContext();

        //Perfom a lookup on the queue
        Queue queue = (Queue) initialContext.lookup("/queue/CalcioEventsQueue");

        //Perform a lookup on the Connection Factory
            /*java:/JmsXA.
        Using this from within a Java EE component specifies that message sending is done as part of the JTA transaction 
         * being used by the component. 
         * If message sending fails, the overall transaction is rolled back and the message is re-sent.*/
        ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("java:JmsXA");

        //Create a JMS Connection
        connection = cf.createConnection();

        //Create a JMS Session
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        //Create a JMS Message Producer
        producer = session.createProducer(queue);
    }

    public void sendMessage(Map<String, String> parametersMap) throws JMSException {
        //Create a MapMessage
        MapMessage mapMessage = session.createMapMessage();
        for (String key : parametersMap.keySet()) {
            mapMessage.setString(key, parametersMap.get(key));
        }
        //Send the Message
        producer.send(mapMessage);
    }

    public void destroy() throws NamingException, JMSException {
        //close JMS resources

        if (initialContext != null) {
            initialContext.close();
        }
        if (connection != null) {
            connection.close();
        }

    }
}
